package com.atguigu.day03;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

// 自定义物理分区
public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(1,2,3,4).setParallelism(1)
                .partitionCustom(
                        // 根据key将数据发送到下游的任务槽中
                        new Partitioner<Integer>() {
                            @Override
                            public int partition(Integer key, int numPartitions) {
                                // key等于0,发送到下游的第1个并行子任务
                                // key等于1,发送到下游的第0个并行子任务
                                return key == 0 ? 1 : 0;
                            }
                        },
                        // 为数据指定key
                        new KeySelector<Integer, Integer>() {
                            @Override
                            public Integer getKey(Integer value) throws Exception {
                                return value % 2;
                            }
                        }
                )
                .print("custom partition").setParallelism(2);

        env.execute();
    }
}
